package com.wwp.info;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.Window;
import android.webkit.JavascriptInterface;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class MainActivity extends Activity {
	SwipeRefreshLayout wipeLayout;
	private WebView webView;
	private final int  HD_TIPS=1;
	private final int  HD_RELOAD=2;
	 String url = "http://120.76.125.165:8081/auther/page/list.html";
    @SuppressWarnings("deprecation")
	@SuppressLint({"SetJavaScriptEnabled", "AddJavascriptInterface", "NewApi"})
    private Handler hd=new Handler(){
    	public void handleMessage(android.os.Message msg) {
    		switch (msg.what) {
			case HD_TIPS:
				  msg("无网络");
				break;
			case HD_RELOAD:
				 webView.reload();
				break;
			}
    		
    	};
    };
    @SuppressLint("NewApi")
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

        webView = (WebView) findViewById(R.id.webView);
        webView.addJavascriptInterface(new JsInterface(this), "AndroidWebView");
        if(NetHelper.IsHaveInternet(this)) {
        	  webView.getSettings().setCacheMode(webView.getSettings().LOAD_DEFAULT);
        }else {
        	msg("无网络");
        	webView.getSettings().setCacheMode(webView.getSettings().LOAD_CACHE_ELSE_NETWORK);
        }
        //设置WebView支持JavaScript
        webView.getSettings().setJavaScriptEnabled(true);
//        String url = "http://192.168.1.11:8020/GSHRSYS/html/java2js.html";
      
        
        webView.getSettings().setDomStorageEnabled(true);

        webView.getSettings().setAppCacheMaxSize(1024*1024*1024);
        webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webView.getSettings().setLoadsImagesAutomatically(true);
        String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();

        webView.getSettings().setAppCachePath(appCachePath);

        webView.getSettings().setAllowFileAccess(true);

        webView.getSettings().setAppCacheEnabled(true);
        webView.setWebViewClient(new WebViewClient() {  
            // 重写此方法表明点击网页里面的链接还是在当前的webview里跳转，不跳到浏览器那边  
            @Override  
            public boolean shouldOverrideUrlLoading(WebView view, String url) {   
                //view.loadUrl(url);  
            	if(!NetHelper.IsHaveInternet(MainActivity.this)){
            		hd.sendEmptyMessage(HD_TIPS);
            		return true;  	
            	}else{
            	    Intent    i= new Intent();
                    i.putExtra("url", url);
                    i.setClass(MainActivity.this,WebFullScreenActivity.class);
                    startActivity(i);
            	}
                return true;  
            }

            // 旧版本，会在新版本中也可能被调用，所以加上一个判断，防止重复显示
            @SuppressWarnings("deprecation")
			@Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                    return;
                }   
                // 在这里显示自定义错误页
                view.loadData("亲，网络连接失败！", "text/html; charset=UTF-8", null);
            }

            // 新版本，只会在Android6及以上调用
            @TargetApi(Build.VERSION_CODES.M)
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { 
                super.onReceivedError(view, request, error);
                if (request.isForMainFrame()){ // 或者： if(request.getUrl().toString() .equals(getUrl()))
                    // 在这里显示自定义错误页
                	  view.loadData("亲，网络连接失败！", "text/html; charset=UTF-8", null);
                }
            }

			@Override
			public void onPageFinished(WebView view, String url) {
				// TODO Auto-generated method stub
				super.onPageFinished(view, url);
				  //隐藏进度条  
				wipeLayout.setRefreshing(false);  
			}
            
            
        });
        webView.loadUrl(url);
        
        
        wipeLayout=(SwipeRefreshLayout) findViewById(R.id.refresh);
		wipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {  
            
            @Override  
            public void onRefresh() {  
                //重新刷新页面  
            	hd.sendEmptyMessage(HD_RELOAD);
            }  
        });  
		wipeLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
				android.R.color.holo_green_light,android.R.color.holo_orange_light);
        //在js中调用本地java方法);
        //在js中调用本地java方法);
        //在js中调用本地java方法
       // webView.addJavascriptInterface(new JsInterface(this), "AndroidWebView");

        //添加客户端支持
     //   webView.setWebChromeClient(new WebChromeClient());
    }

    private class JsInterface {
        private Context mContext;

        public JsInterface(Context context) {
            this.mContext = context;
        }

        //在js中调用window.AndroidWebView.showInfoFromJs(name)，便会触发此方法。
        @JavascriptInterface
        public void showInfoFromJs(String name) {
//        	webView.reload();
//        	hd.sendEmptyMessage(HD_RELOAD);
            Toast.makeText(mContext, name, Toast.LENGTH_SHORT).show();
          
        }
    }

    //在java中调用js代码
//    public void sendInfoToJs(View view) {
//        String msg = ((EditText) findViewById(R.id.input_et)).getText().toString();
//        //调用js中的函数：showInfoFromJava(msg)
//        webView.loadUrl("javascript:showInfoFromJava('" + msg + "')");
//    }
    
    public void msg(String str){
    	Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
    }
    
    @Override
    protected void onDestroy() {
    	// TODO Auto-generated method stub
    	super.onDestroy();
    	if(webView!=null){
    		webView.removeAllViews();
    		webView=null;
    	}
    }
}
